<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="下单时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeOrderDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="订单金额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入订单金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="queryParams.paymentMethod" placeholder="请选择支付方式" clearable>
          <el-option
            v-for="dict in pay_method"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orders:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orders:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="下单时间" align="center" prop="orderDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="重量(kg)" align="center" prop="weight" /> -->
      <el-table-column label="运费" align="center" prop="price"/>
      <el-table-column label="订单总金额" align="center" prop="totalAmount" />
      <el-table-column label="订单状态" align="center" prop="status"/>
      <el-table-column label="支付方式" align="center" prop="paymentMethod"/>
      <el-table-column label="地址" align="center" class-name="small-padding fixed-width" width="280">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleAddressDetail(scope.row)">地址详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="评论" align="center" class-name="small-padding fixed-width" width="280">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleComment(scope.row)"  v-show="showReviewsButton" >评论</el-button>
        </template>
      </el-table-column>showReviewsButton
      <el-table-column label="发货" align="center" width="120">
  <template #default="scope">
    <el-button 
      v-if="showAddButton" 
      type="primary" 
      size="small" 
      @click="handleShip(scope.row)"
    >发货</el-button>
    <el-tag v-else type="success">已发货</el-tag>
  </template>
</el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['orders:orders:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />


  <!-- 发货对话框 -->
<!-- 发货对话框 - 纯文本输入版 -->
<el-dialog title="订单发货" v-model="shipDialogVisible" width="600px" append-to-body>
  <el-form ref="shipFormRef" :model="shipForm" :rules="shipRules" label-width="80px">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="省份" prop="province">
          <el-input v-model="shipForm.province" placeholder="请输入省份"/>
        </el-form-item>
      </el-col>
      <el-col :span="8">  
        <el-form-item label="城市" prop="city">
          <el-input v-model="shipForm.city" placeholder="请输入城市"/>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="区县" prop="district">
          <el-input v-model="shipForm.district" placeholder="请输入区县"/>
        </el-form-item>
      </el-col>
    </el-row>
    
    <el-form-item label="详细地址" prop="detailAddress">
      <el-input 
        v-model="shipForm.detailAddress" 
        placeholder="街道门牌号等详细地址"
      />
    </el-form-item>
  </el-form>
  
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="shipDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitShip">确认发货</el-button>
    </div>
  </template>
</el-dialog>
    <!-- 收寄件人详情对话框 -->
    <el-dialog title="地址详情" v-model="addressDialogVisible" width="700px" append-to-body>
      <el-tabs v-model="activeAddressTab">
        <el-tab-pane label="收件人信息" name="sender">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="姓名">{{ senderInfo.contactName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ senderInfo.contactPhone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="地址">
              {{ formatAddress(senderInfo) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        
        <el-tab-pane label="寄件人信息" name="receiver">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="姓名">{{ receiverInfo.contactName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ receiverInfo.contactPhone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="地址">
              {{ formatAddress(receiverInfo) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
      
      <div class="order-summary">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="运费">10元</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addressDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 评论对话框 -->
    <el-dialog title="订单评论" v-model="commentDialogVisible" width="500px" append-to-body>
      <el-form ref="commentFormRef" :model="commentForm" :rules="commentRules" label-width="80px">
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="commentForm.rating" :max="5" show-text></el-rate>
        </el-form-item>
        <el-form-item label="评论内容" prop="content">
          <el-input v-model="commentForm.content" type="textarea" rows="4" placeholder="请输入您的评论"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="commentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitComment">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="收件人ID" prop="recipientId">
          <el-input v-model="form.recipientId" placeholder="请输入收件人用户ID" />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderDate">
          <el-date-picker clearable
            v-model="form.orderDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="商品重量(kg)" prop="weight">
          <el-input-number 
            v-model="form.weight" 
            :min="0.1" 
            :step="0.1" 
            :precision="2"
            placeholder="请输入商品重量"
          />
        </el-form-item>
        <el-form-item label="运费" prop="freight">
          <el-input v-model="form.freight" placeholder="系统自动计算" readonly />
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入订单总金额" />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态">
            <el-option
              v-for="dict in order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="form.paymentMethod" placeholder="请选择支付方式">
            <el-option
              v-for="dict in pay_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货地址" prop="senderAddress">
          <el-input v-model="form.senderAddress" placeholder="请输入发货地址" />
        </el-form-item>
        <el-form-item label="收货地址" prop="shippingAddress">
          <el-input v-model="form.shippingAddress" type="textarea" placeholder="请输入收货地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/orders/orders";
import { addReviews } from "@/api/reviews/reviews";
import { updateLogisticsaddress,listLogisticsaddress } from "@/api/logisticsaddress/logisticsaddress";
import Cookies from 'js-cookie';  //cookies的使用要求引入
const { proxy } = getCurrentInstance();
import {  listOrderdetails } from "@/api/orderdetails/orderdetails";
const { order_status, pay_method } = proxy.useDict('order_status', 'pay_method');
// 订单数据
const ordersList = ref([]);
const showAddButton = ref(false); 
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeOrderDate = ref([]);

// 收寄件人详情相关
const addressDialogVisible = ref(false);
const showReviewsButton = ref(true);
const activeAddressTab = ref('sender');
const currentOrder = ref({});
const senderInfo = ref({});
const receiverInfo = ref({});

// 评论相关
const commentDialogVisible = ref(false);
const commentFormRef = ref(null);

// 发货相关
const shipDialogVisible = ref(false);
const shipFormRef = ref(null);

const data = reactive({
  shipForm: {
    orderId: null,
    listLogisticsId:"",
    shippingAddress: '',
    province:"",
    city:"",
    district:"",
    detailAddress:"",
    addressId:null

  },
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderDate: null,
    totalAmount: null,
    status: null,
    paymentMethod: null,
    userName:null,
  },
  query: {
    pageNum: 1,
    pageSize: 10,
    logisticsId:"",
    addressType:null,
    contactName:null,
    contactPhone:null,
    currentLocation:null
  },
  commentForm: {
    orderId: null,
    userId: null,
    rating: null,
    content: ''
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    recipientId: [
      { required: true, message: "收件人ID不能为空", trigger: "blur" }
    ],
    weight: [
      { required: true, message: "商品重量不能为空", trigger: "blur" }
    ],
    totalAmount: [
      { required: true, message: "订单总金额不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "请选择订单状态", trigger: "change" }
    ],
    shippingAddress: [
      { required: true, message: "请输入收货地址", trigger: "blur" }
    ],
    rating: [
      { required: true, message: '请选择评分', trigger: 'change' }
    ],
    content: [
      { required: true, message: '请输入评论内容', trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules, commentForm ,shipForm,query} = toRefs(data);

/** 查询订单列表 */
function getList() {
  loading.value = true;
  if(Cookies.get("username")=="sqlstudent1"||Cookies.get("username")=="admin"){
        showAddButton.value=true;
        showReviewsButton.value=false;
      }
  queryParams.value.params = {};
  if (null != daterangeOrderDate && '' != daterangeOrderDate) {
    queryParams.value.params["beginOrderDate"] = daterangeOrderDate.value[0];
    queryParams.value.params["endOrderDate"] = daterangeOrderDate.value[1];
  }

  const userName="sqlstudent";
   queryParams.value.userName=userName;
  listOrders(queryParams.value).then(response => {
    ordersList.value = response.rows;
    console.log(response.rows);
    ordersList.value.forEach(item => {

  item.price = 10; // 假设weight字段存在
});
total.value = response.total;
    loading.value = false;
    ///////////////////////////////////////
  
});
    
}

/** 格式化地址信息 */
function formatAddress(address) {
  if (!address) return '-';
  return [address.province, address.city, address.district, address.detailAddress].filter(Boolean).join('') || '-';
}

/** 获取收寄件人详情 */
function handleAddressDetail(row) {
  currentOrder.value = row;
  loading.value = true;
  
  // 获取物流地址列表
  listLogisticsaddress({ relatedOrderId: row.orderId }).then(res => {
    const addresses = res.rows || [];
    
    // 分离寄件人和收件人信息
    const sender = addresses.find(a => a.addressType === 'SENDER');
    const receiver = addresses.find(a => a.addressType === 'RECIPIENT');
    
    senderInfo.value = sender || {};
    receiverInfo.value = receiver || {};
    
    addressDialogVisible.value = true;
    getList();
  }).catch(err => {
    proxy.$modal.msgError("获取地址信息失败: " + (err.message || err));
  }).finally(() => {
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    userId: null,
    recipientId: null,
    orderDate: null,
    weight: null,
    freight: null,
    totalAmount: null,
    status: null,
    paymentMethod: null,
    senderAddress: null,
    shippingAddress: null
  };
  proxy.resetForm("ordersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeOrderDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _orderId = row.orderId || ids.value;
  getOrders(_orderId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单";
    getList();
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if (valid) {
      if (form.value.orderId != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal.confirm('是否确认删除订单编号为"' + _orderIds + '"的数据项？').then(function() {
    getList();
    return delOrders(_orderIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orders/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

// 处理评论按钮点击
// 处理评论按钮点击
function handleComment(row) {
  const query = {
    orderId: row.orderId
  };
  
  console.log(row); // 正确的日志输出
  
  listOrderdetails(query).then(response => {
    console.log(response.rows);
    commentForm.value.productId = response.rows[0].productId; // 修正为 response.rows
    commentForm.value.userName = row.userName;
    commentDialogVisible.value = true;
    getList();
  }).catch(error => {
    console.error("获取订单详情失败:", error);
  });
}

// 提交评论
function submitComment() {
  commentForm.value.comment=commentForm.value.content;
  console.log(commentForm.value)
  commentFormRef.value.validate(valid => {
    if (valid) {
      loading.value = true;
      addReviews( commentForm.value ).then(() => {
        proxy.$modal.msgSuccess("评论提交成功");
        commentDialogVisible.value = false;
        getList();
      }).catch(err => {
        proxy.$modal.msgError("评论提交失败: " + (err.message || err));
      }).finally(() => {
        loading.value = false;
      });
    }
  });
}

// 添加方法
function handleShip(row) {
  shipForm.value.orderId = row.orderId;
  shipForm.value.listLogisticsId = row.orderId;
  query.value.logisticsId = row.orderId;
  shipDialogVisible.value = true;
}

function submitShip() {
  listLogisticsaddress(query.value).then(response => {
    shipForm.value.addressId = response.rows[0].addressId;
    return updateLogisticsaddress(shipForm.value);
  }).then(() => {
    // 更新订单状态为已发货
    return updateOrders({
      orderId: shipForm.value.orderId,
      status: 'SHIPPED'  // 确保这个值与您的状态字典一致
    });
  }).then(() => {
    shipDialogVisible.value = false;
    proxy.$modal.msgSuccess("发货成功");
    
    // 强制更新当前行的状态显示
    const index = ordersList.value.findIndex(item => item.orderId === shipForm.value.orderId);
    if (index !== -1) {
      ordersList.value[index].status = 'SHIPPED';
      // 使用Vue.set或直接赋值都可以，因为您使用的是ref
      // 为了确保响应性，可以这样：
      ordersList.value = [...ordersList.value];
    }
    
    // 同时刷新列表数据
    getList();
  }).catch(err => {
    proxy.$modal.msgError("发货失败: " + (err.message || err));
  });
}


getList();
</script>

<style scoped>
.order-summary {
  margin-top: 20px;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-descriptions-item__label {
  width: 100px;
}

.el-tabs {
  margin-bottom: 20px;
}
</style>